/* eslint no-unused-vars:0 */
import React from 'react';
import PubSub from 'pubsub-js';
import './../index.less';

import { Link } from 'react-router-dom';
import { Row, Col, Icon, Upload, message } from 'antd';
import { Table, Button, Divider, Popconfirm, Tag } from 'antd';

import PDFViewer from './PDFViewer';

const url = 'report';
export default class PublicSentiment extends React.Component {
    constructor(props) {
        super(props);
    }

    state = {
        data: [],
        columns: [
            {
                title: '舆情分析报告',
                key: 'originalName',
                inputType: 'input',
                dataIndex: 'originalName',
                editable: true
            },
            {
                title: '作者',
                key: 'authorName',
                inputType: 'input',
                dataIndex: 'authorName',
                editable: true
            },
            {
                title: '预览',
                key: 'reportFile',
                render: (text, record) => {
                    return (
                        <div>
                            {this.state.publicSentiment.name == '工作简报' ? (
                                '不支持预览'
                            ) : (
                                <a he onClick={this.readPdf.bind(text, record)}>
                                    查看文档内容
                                </a>
                            )}
                        </div>
                    );
                }
            },
            {
                title: '是否开放',
                key: 'isOpen',
                render: (text, record) => {
                    let color = '';
                    let open = record.open;
                    if (!open) {
                        color = 'volcano';
                    }
                    return (
                        <Tag color={color} key={open}>
                            {open ? '开放' : '保密'}
                        </Tag>
                    );
                }
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => {
                    return (
                        <div>
                            <a onClick={this.handleOpen.bind(text, record)}>
                                设置开放
                            </a>
                            <Divider type="vertical" />
                            {this.state.publicSentiment.name == '工作简报' ? (
                                '暂不支持下载'
                            ) : (
                                <a
                                    href={
                                        localStorage.getItem('url') +
                                        '/report/onlineView/' +
                                        record.saveName
                                    }
                                    rel="noopener noreferrer"
                                    target="_Blank">
                                    下载文档
                                </a>
                            )}
                            <Divider type="vertical" />
                            <Popconfirm
                                title={'确定要删除这条数据?'}
                                onConfirm={() =>
                                    this.handleDelete(text, record)
                                }>
                                <a>删除</a>
                            </Popconfirm>
                        </div>
                    );
                }
            }
        ],
        publicSentiment: {
            id: ''
        },
        page: 1,
        size: 5,
        total: 0
    };

    componentDidMount() {
        let temp = JSON.parse(sessionStorage.getItem('showReport'));
        this.setState({
            publicSentiment: temp
        });
        this.getData(temp.id, 1);
    }

    getData = (message, page) => {
        this.$post(url + '/adminFindByPublic', {
            publicSentimentId: message,
            page: page,
            size: this.state.size
        })
            .then((res) => {
                if (res) {
                    var data = res.obj;
                    for (var i = 0; i < data.length; i++) {
                        data[i]['key'] = data[i].id;
                    }
                    this.setState({
                        data: data,
                        total: res.maxCount
                    });
                } else this.$showNotification('error', '获取数据失败');
            })
            .catch((e) => {
                console.log(e);
            });
    };

    readPdf = (text, record) => {
        PubSub.publish('readPdf', text.saveName);
        sessionStorage.setItem('readPdf', text.saveName);
    };

    handleOpen = (data, record) => {
        console.log(data);
        this.$post(url + '/open', data.id)
            .then((res) => {
                if (res) {
                    this.getData(
                        this.state.publicSentiment.id,
                        this.state.page
                    );
                    this.$showNotification('success', '设置成功');
                } else this.$showNotification('error', '设置失败');
            })
            .catch((e) => {
                console.log(e);
            });
    };

    handleDelete = (data, record) => {
        console.log(data);
        this.$post(url + '/delete', data.id)
            .then((res) => {
                if (res.status != '500') {
                    this.getData(
                        this.state.publicSentiment.id,
                        this.state.page
                    );
                    this.$showNotification('success', '删除成功');
                } else this.$showNotification('error', '获取数据失败');
            })
            .catch((e) => {
                console.log(e);
            });
    };

    handleChange = (info) => {
        let fileList = info.fileList.slice();
        let file = fileList[fileList.length - 1];

        if (file.status !== 'uploading') {
            console.log(file, fileList);
        }

        if (file.status === 'done') {
            if (file.response) {
                var response = file.response;
                if (response.code === 0) {
                    file.status = 'success';
                    message.success(`${file.name} 文件上传成功`);
                } else {
                    file.status = 'error';
                    message.success(`${file.name} 文件上传失败`);
                }
            }
        }

        this.setState({
            fileList: fileList
        });

        this.getData(this.state.publicSentiment.id, this.state.page);
    };

    pageChange = (page, size) => {
        this.setState({
            page: page
        });
        this.getData(this.state.publicSentiment.id, page);
    };

    goback() {
        this.props.history.goBack();
    }

    render() {
        const url = localStorage.getItem('url');

        console.log();
        const props = {
            name: 'file',
            action: url + '/report/upload/',
            accept: '.doc,.docx,.pdf',
            data: {
                publicSentimentId: this.state.publicSentiment.id,
                title: 'test'
            },
            headers: {
                jwtToken: localStorage.getItem('jwtToken'),
                userId: localStorage.getItem('userId')
            },
            onChange: this.handleChange
        };

        return (
            <div className="body">
                <span className="opinion-body">舆情报告管理</span>
                <Row>
                    <Button onClick={this.goback.bind(this)}>返回上一层</Button>
                </Row>
                <Row className="overview-row2">
                    <Upload {...props} fileList={this.state.fileList}>
                        <Button>
                            <Icon type="upload" /> 上传报告
                        </Button>
                    </Upload>
                    <Table
                        columns={this.state.columns}
                        dataSource={this.state.data}
                        pagination={{
                            current: this.state.page,
                            pageSize: this.state.size,
                            total: this.state.total,
                            onChange: this.pageChange
                        }}
                    />
                    <PDFViewer />
                </Row>
            </div>
        );
    }
}
